<template>
  <main-layout
    :showHome="!isFromList"
    :showBack="isFromList"
    :title="`${isEdit ? '编辑' : '新增'}项目信息`"
  >
    <div class="edit-box">
      <van-form @submit="onSubmit">
        <!-- 基本信息 -->
        <div class="formTitle">基本信息</div>
        <van-field
          v-model="formObj.name"
          type="text"
          label="项目名"
          placeholder="请输入项目名"
          :rules="[{ required: true, message: '请输入项目名' }]"
        />
        <van-field
          v-model="formObj.signTime"
          type="text"
          label="签订日期"
          placeholder="请选择签订日期"
          readonly
          :rules="[{ required: true }]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              color="#ff5b02"
              native-type="button"
              @click="timeShow = true"
              >选择日期</van-button
            >
          </template>
        </van-field>
        <van-field
          v-model="cityName"
          type="text"
          label="地市"
          placeholder="请选择地市"
          readonly
          :rules="[{ required: true }]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              color="#ff5b02"
              native-type="button"
              @click="cityShow = true"
              >选择地市</van-button
            >
          </template>
        </van-field>
        <van-field
          v-model="formObj.address"
          type="text"
          label="详细地址"
          placeholder="请输入详细地址"
          :rules="[{ required: true, message: '请输入详细地址' }]"
        />
        <van-field
          v-model="formObj.liableName"
          type="text"
          label="负责人"
          placeholder="请选择负责人"
          readonly
          :rules="[{ required: true }]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              color="#ff5b02"
              native-type="button"
              @click="pickPerson()"
              >选择负责人</van-button
            >
          </template>
        </van-field>

        <!-- 业主信息 -->
        <div class="formTitle">业主信息</div>
        <van-field
          v-model="formObj.ownerName"
          type="text"
          label="业主"
          placeholder="请输入业主"
          :rules="[{ required: true, message: '请输入业主' }]"
        />
        <van-field
          v-model="formObj.ownerAddress"
          type="text"
          label="业主地址"
          placeholder="请输入业主地址"
          :rules="[{ required: true, message: '请输入业主地址' }]"
        />
        <van-field
          v-model="formObj.ownerPhone"
          type="text"
          label="联系电话"
          placeholder="请输入联系电话"
          :rules="[
            { required: true, message: '请输入联系电话' },
            { pattern, message: '请输入正确的联系电话' },
          ]"
        />

        <!-- 备注信息 -->
        <div class="formTitle">备注信息</div>
        <van-field
          v-model="formObj.remark"
          type="textarea"
          autosize
          label="备注"
          placeholder="请输入备注"
        />

        <div style="margin: 12px 0px">
          <van-button
            round
            block
            type="info"
            native-type="submit"
            color="#ff5b02"
            >提交</van-button
          >
        </div>
      </van-form>

      <!-- 选择日期组件 -->
      <van-calendar v-model="timeShow" @confirm="onPickTime" color="#ff5b02" />
      <!-- 选择地市组件 -->
      <van-popup
        v-model="cityShow"
        round
        position="bottom"
        :close-on-click-overlay="false"
        :style="{ height: '45%' }"
      >
        <van-area
          title="选择地市"
          :area-list="areaList"
          @cancel="cityShow = false"
          @confirm="onPickCity"
        />
      </van-popup>
      <!-- 选择负责人组件 -->
      <van-popup
        v-model="personShow"
        round
        position="left"
        :close-on-click-overlay="false"
        :style="{ height: '100%', width: '90%' }"
      >
        <div class="user-box">
          <header>
            <input
              type="text"
              placeholder="输入需要过滤的名字"
              v-model="personQuery.name"
            />
            <button @click="pickPerson(true)">
              <img src="../../images/search.png" alt="" />
            </button>
          </header>
          <ul @scroll="scrollEvt">
            <li
              v-for="item in personList"
              :key="item.id"
              @click="pickUser(item)"
            >
              {{ item.name }} {{ item.dept }} {{ item.duties }}
            </li>
            <li class="more">
              {{
                loading
                  ? "加载中..."
                  : hasMore
                  ? "上滑加载更多"
                  : "不要滑了，没有了"
              }}
            </li>
          </ul>
        </div>
      </van-popup>
    </div>
  </main-layout>
</template>
<script>
import { dateFormat } from "../../util/index";
import { areaList } from "@vant/area-data";
import {
  getPersonListApi,
  projectSaveApi,
  projectUpdateApi,
} from "../../apis/ProjectApi";
export default {
  data() {
    return {
      loading: false,
      hasMore: true,
      // 是否来自项目管理页面
      isFromList: false,
      // 是否通过编辑按钮过来
      isEdit: false,
      // 是否显示选择日期组件
      timeShow: false,
      // 是否显示选择地市组件
      cityShow: false,
      // 是否显示选择负责人组件
      personShow: false,
      areaList,
      // 表单v-modoule
      formObj: {
        id: "",
        name: "",
        liableId: "",
        liableName: "",
        signTime: "",
        province: "",
        city: "",
        county: "",
        address: "",
        ownerId: "",
        ownerName: "",
        ownerAddress: "",
        ownerPhone: "",
        remark: "",
      },
      // 查询用户信息的查询对象
      personQuery: {
        name: "",
        page: 1,
        size: 20,
      },
      // 用户列表
      personList: [],
      // 地市
      cityName: "",
      // 正则校验电话号码输入是否正确
      pattern: /^1[3-9]{1}[0-9]{9}$/,
    };
  },
  created() {
    this.isFromList = !!this.$route.query.from;
    this.isEdit = !!this.$route.query.id;
    this.editObjList();
  },
  methods: {
    // 如果从编辑页面过来，处理数据
    //  this.$route.params.row.name
    editObjList() {
      if (!!this.isEdit) {
        this.formObj.id = this.$route.params.row.id;
        this.formObj.name = this.$route.params.row.name;
        this.formObj.signTime = dateFormat(
          this.$route.params.row.signTime,
          "yyyy-MM-dd"
        );
        this.cityName = `${this.$route.params.row.city}/${this.$route.params.row.county}/${this.$route.params.row.province}`;
        this.formObj.address = this.$route.params.row.address;
        this.formObj.liableName = this.$route.params.row.liableName;
      }
    },
    // 提交按钮时间
    async onSubmit() {
      let citys = this.cityName.split("/");
      this.formObj.province = citys[0];
      this.formObj.city = citys[1];
      this.formObj.county = citys[2];
      if (!!this.isEdit) {
        let resultUpdate = await projectUpdateApi(this.formObj);
        if (resultUpdate.code === 200) {
          this.$toast.success("保存成功");
        } else {
          this.$toast.fail("保存失败");
        }
      } else {
        let result = await projectSaveApi(this.formObj);
        if (result.code === 200) {
          this.$toast.success("保存成功");
        } else {
          this.$toast.fail("保存失败");
        }
      }
    },
    // 获取时间
    onPickTime(date) {
      this.timeShow = false;
      this.formObj.signTime = dateFormat(date, "yyyy-MM-dd");
    },
    // 获取地市
    onPickCity(arr) {
      this.cityName = arr
        .reduce(function (res, item) {
          res.push(item.name);
          return res;
        }, [])
        .join("/");
      this.cityShow = false;
    },
    // 通过isSearch的值判断是查询还是点击按钮获取的用户列表
    pickPerson(isSearch) {
      this.personQuery.page = 1;
      this.personList = [];
      this.loading = true;
      this.getPersonList();
      if (!isSearch) {
        this.personShow = true;
        this.personQuery.name = "";
      }
    },
    // 获取用户列表
    async getPersonList() {
      let result = await getPersonListApi(this.personQuery);
      if (result.code === 200) {
        this.personList = this.personList.concat(result.data.rows);
        // 计算是否还有数据没有从后端获取回来: 当前页面 * 每一页数据 一定要小于 总数据
        this.hasMore =
          this.personQuery.page * this.personQuery.size < result.data.total;
      }
      // 因为vue是虚拟dom，而虚拟dom更新和赋值是异步，所以再关闭加载状态时，需要延迟
      setTimeout(() => {
        this.loading = false;
      });
    },
    // 滚动加载 -- 谁是容器(ul)，来注册滚动事件
    scrollEvt() {
      let target = window.event.target;
      // 计算是否已经滚动到底部：容器展示高度 + 已经滚动上去的距离 === 容器的真实高度
      let isBottom =
        target.clientHeight + target.scrollTop + 20 > target.scrollHeight;
      // 因为要做请求节流(第一次请求没有结束的情况下，不能发起第二次请求)，必须有更多数据，一定要滚动到底部的时候才能执行加载
      if (!this.loading && this.hasMore && isBottom) {
        // 开启节流阀门
        this.loading = true;
        this.personQuery.page += 1;
        this.getPersonList();
      }
    },
    // 点击要选择的项，将值赋值
    pickUser(user) {
      this.formObj.liableId = user.id;
      this.formObj.liableName = user.name;
      this.personShow = false;
    },
  },
};
</script>
<style lang="less" scoped>
@import "./index.less";
</style>